/**
 * @global
 */
var WebIMTabEvent = (function (localStorage) {
  var events = {};
  var prefix = '_event_';
  // 监听 localStorage 变化
  if ('onstorage' in document) {
    // 兼容IE8
    document.attachEvent('onstorage', function () {
      var event = {};
      event.key = localStorage.getItem('_last_storage_event_key');
      event.newValue = localStorage.getItem(event.key);
      onStorage(event);
    });
  } else {
    window.addEventListener('storage', onStorage);
  }

  var valuePrefix = 'val-' + new Date().getTime();
  var broadcastId = 0;


  function broadcast(type, data) {
    if (!type) {
      return;
    }
    var key = prefix + type;
    // 兼容IE8
    if ('onstorage' in document) {
      localStorage.setItem('_last_storage_event_key', key);
    }

    // storage 只支持字符串存储
    if (typeof data == 'object') {
      data = JSON.stringify(data);
    }

    broadcastId++;
    data = valuePrefix + data + '-' + broadcastId;
    localStorage.setItem(key, data);
  }

  function on(type, callback) {
    if (!events[type]) {
      events[type] = [];
    }
    if (typeof callback == 'function') {
      events[type].push(callback);
    }
  }

  function onStorage(event) {
    var key = event.key;
    var value = event.newValue;
    if (!key || !value || key.indexOf(prefix) != 0) {
      return;
    }
    if (value.indexOf('val-') != 0) {
      return;
    }
    var valPrefix = value.substr(0, valuePrefix.length);
    if (valPrefix == valuePrefix) {
      return;
    }
    var suffixIndex = value.lastIndexOf('-');

    // 截取真实的数据
    value = value.substring(valPrefix.length, suffixIndex);

    var type = key.substr(prefix.length);
    var data = value;
    try {
      data = JSON.parse(value);
    } catch (e) {
      // 解析失败，去除前后空格；
      data = $.trim(value);
    }
    // 触发事件
    if (events[type]) {
      var fns = events[type];
      for (var i = 0; i < fns.length; i++) {
        var fn = fns[i];
        fn(data);
      }
    }
  }

  return {
    /**
     * 往其他Tab广播事件
     * @param {String} type 事件类型
     * @param {String|Object} data 数据
     * @example
     * WebIMTabEvent.broadcast('event', data)
     */
    broadcast: broadcast,
    /**
     * 注册事件，处理其他Tab发起的广播事件
     * @param {String} type 事件类型
     * @param {Function} callback 消息处理函数
     * @example
     * WebIMTabEvent.on('event', function(data){
     *  // data
     * });
     */
    on: on
  };
})(localStorage);
